package top.maof.book.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
import top.maof.book.model.Perm;
import top.maof.book.model.Role;
import top.maof.book.result.ApiResponse;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.service.PermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CodeX4J.
 */
@Controller
@RequestMapping("perm")
@RequiresRoles({Role.ADMIN})
@ResponseBody
public class PermController {
    @Autowired
    private PermService permService;

    @ApiOperation("新建")
    @PostMapping("/create")
    public ApiResponse create(@RequestBody Perm perm) {
        return ApiResponse.success(permService.save(perm));
    }

    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable Integer id) {
        permService.removeById(id);
        return ApiResponse.success(null);
    }

    @ApiOperation("批量删除")
    @GetMapping("/delete/batch")
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String [] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        permService.removeBatchByIds(idList);
        return ApiResponse.success(null);
    }

    @ApiOperation("根据ID修改")
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody Perm perm) {
        permService.updateById(perm);
        return ApiResponse.success(null);
    }

    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse<PageData<Perm>> findPage (@RequestBody PageWrap<Perm> pageWrap) {
        return ApiResponse.success(permService.findPage(pageWrap));
    }

    @ApiOperation("根据ID查询")
    @GetMapping("/{id}")
    public ApiResponse findById(@PathVariable Integer id) {
        return ApiResponse.success(permService.getById(id));
    }

    @RequestMapping("add")
    public int add(Perm perm) {
        return permService.add(perm);
    }

    @RequestMapping("find")
    public Perm find(int id) {
        return permService.find(id);
    }

    @RequestMapping("update")
    public int update(Perm perm) {
        return permService.update(perm);
    }

    @RequestMapping("delete")
    public int delete(int id) {
        return permService.delete(id);
    }
}
